﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using System.Xml.Linq;
using Yonkly.Models;
using Yonkly.Services;
using JsonResult = System.Web.Mvc.JsonResult;

namespace Yonkly.Controllers
{
    public class TwitterController : BaseController
    {
        private int TweetsImported = 0;

        //private int TweetsImported
        //{
        //    get
        //    {
        //        if (TempData["TweetsImported"] == null)
        //        {
        //            TempData["TweetsImported"] = 0;
        //        }
        //        return (int)TempData["TweetsImported"];
        //    }
        //    set
        //    {

        //        TempData["TweetsImported"] = value;
        //    }
        //}

        public ActionResult Import()
        {
            // Add action logic here
            return View(GetBaseViewData());
        }

        public JsonResult GetImportStatus()
        {
            var temp = TweetsImported;
            return Json(new
            {
                TweetsImported = temp
            });
        }
        public JsonResult BeginImport()
        {
            var results = new JsonData();
            TweetsImported = 0;
            try
            {
                var tweetCount = 200;
                var page = 1;
                ImportTweets(page, tweetCount);
                results.isSuccessful = true;
                //ViewData["TweetsImported"] = TweetsImported;
            }
            catch (Exception)
            {
                results.isSuccessful = false;
                results.errorMessage = "An unknown error occured while importing your tweets.";
            }

            return Json(new
            {
                results.isSuccessful,
                results.errorMessage,
                TweetsImported
            });

        }

        private void ImportTweets(int page, int tweetCount)
        {
            try
            {
                //get first page
                var tweets = GetTweets(page, tweetCount);
                ImportTweets(tweets);


                while (tweets.Count() == tweetCount)
                {
                    //incrememnt page
                    page++;
                    tweets = GetTweets(page, tweetCount);
                    ImportTweets(tweets);

                }
            }
            catch (WebException ex)
            {
                if (ex.Status == WebExceptionStatus.ProtocolError && tweetCount != 1)
                {
                    //ignore this error
                    //this error is due to twitter limiting to only X numbers of pages
                }
            }
        }

        private void ImportTweets(IEnumerable<TwitterStatus> tweets)
        {
            foreach (var tweet in tweets)
            {

                using (var dc = new YonklyDataContext())
                {
                    //todo make sure it hasn't been imported before
                    var twitterId = tweet.Id;
                    if (dc.MessageDetails.Count(md => md.TwitterId == twitterId) != 0)
                        continue;
                    var msg = new Message
                                  {
                                      Text = tweet.Text.Replace("\r\n", " "),
                                      ModifiedOn = tweet.CreatedAt,
                                      CreatedOn = tweet.CreatedAt,
                                      SenderId = LoggedInUserId,
                                      Type = ((int)MessageTypes.Text),
                                      Source = "twitter"
                                  };
                    dc.Messages.InsertOnSubmit(msg);
                    dc.SubmitChanges();

                    var details = new MessageDetail()
                                      {
                                          CreatedOn = DateTime.Now.ToUniversalTime(),
                                          ModifiedOn = DateTime.Now.ToUniversalTime(),
                                          MessageId = msg.MessageId,
                                          TwitterFavorited = tweet.Favorited,
                                          TwitterId = twitterId,
                                          TwitterReplyStatusId = tweet.ReplyStatusId,
                                          TwitterReplyUserId = tweet.ReplyUserId

                                      };
                    dc.MessageDetails.InsertOnSubmit(details);
                    dc.SubmitChanges();
                    TweetsImported++;
                }
            }
        }

        private IEnumerable<TwitterStatus> GetTweets(int page, int count)
        {
            var t = new Twitter();
            var p = ProfileController.GetUserSettings(LoggedInUserId);
            var xml = t.GetUserTimeline(p.TwitterUserName,
                p.TwitterUserName, p.TwitterUserName,
                Twitter.OutputFormatType.XML, page, count);

            TextReader tr = new StringReader(xml);

            var doc = XDocument.Load(tr);
            return from status in doc.Descendants("status")
                   select new TwitterStatus()
                              {
                                  Text = status.Element("text").Value,
                                  Source = status.Element("source").Value,
                                  Id = status.Element("id").Value,
                                  CreatedAt = status.Element("created_at").Value.ToDateFromTwitterDate(),
                                  Favorited = string.IsNullOrEmpty(status.Element("favorited").Value) ? false : Convert.ToBoolean(status.Element("favorited").Value)
                              };
        }
    }
}
